<template>
  <form class="body1" style="background-color: #f9f7f7;background-size: cover;">
    <el-row justify="center">
      <el-col :span="4" style="margin: auto"><el-icon size="128px" color="#3F72AF" @click="last"><ArrowLeftBold /></el-icon></el-col>
      <el-col :span="16" style="justify-content: center;text-align: center;">
        <h1>上传您的简历</h1>
        <div class="card3">
          <el-row style="margin-top:50px ">
            <el-upload
                class="upload-demo"
                drag
                style="margin: auto;width: 500px"
                action="#"
                multiple
                :on-change="handleFileChange"
                :on-remove="handleRemove"
                accept=".pdf,.docx,.jpg,.jpeg,.png,.gif,.bmp,.svg"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拽去文件到这里或 <em>点我进行上传</em>
              </div>
            </el-upload>
          </el-row>
          <el-row>
            <div class="el-upload-list__item-container">
              <div v-for="file in fileList" :key="file.uid" class="el-upload-list__item">
                <div>
                  <div v-if="isImage(file.name)">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                  </div>
                  <div v-else>
                    <i class="el-icon-document"></i>
                    <span>{{ file.name }}</span>
                    <button @click.prevent="openFile(file)">打开文件</button>
                    <button @click="removeFile(file)">删除文件</button>
                  </div>
                </div>
              </div>
            </div>
          </el-row>
        </div>
      </el-col>
      <el-col :span="4" style="margin: auto"><el-icon size="128px" color="#3F72AF" @click="next"><ArrowRightBold /></el-icon></el-col>
    </el-row>
    <el-dialog v-model="dialogVisible">
      <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%; height: auto;" />
    </el-dialog>
  </form>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { ArrowLeftBold, ArrowRight, ArrowRightBold, UploadFilled, Delete, Download, ZoomIn } from "@element-plus/icons-vue";
import router from "@/router";
import { ElImage } from 'element-plus';
import mammoth from 'mammoth';

import JSZip from 'jszip';

const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const disabled = ref(false);
const docxContent = ref('');
const plainText = ref('');

const last = () => {
  // 这里添加你的登录逻辑
  // 假设登录成功后，跳转到仪表盘页面
  router.push('/first');
};

const next = () => {
  // 这里添加你的登录逻辑
  // 假设登录成功后，跳转到仪表盘页面
  router.push('/resume');
};

const handleFileChange = async (file, fileListData) => {
  const isFileExists = fileList.value.some(f => f.uid === file.uid);
  if (!isFileExists) {
    file.url = URL.createObjectURL(file.raw);
    fileList.value.push(file);
    localStorage.setItem('fileList', JSON.stringify(fileList.value));

    // 读取文件内容
    if (file.name.endsWith('.docx')) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        const arrayBuffer = e.target.result;
        try {
          // 使用 mammoth.js 转换 docx 内容为 HTML
          const result = await mammoth.convertToHtml({ arrayBuffer });
          const tempDiv = document.createElement('div');
          tempDiv.innerHTML = result.value;
          plainText.value = tempDiv.textContent;
          console.log('DOCX文件纯文本内容:', plainText.value);
        } catch (error) {
          console.error('读取 DOCX 文件出错:', error);
        }
      };
      reader.readAsArrayBuffer(file.raw);
    }
  }
};

const handleRemove = (file) => {
  // 打印接收到的文件对象结构，用于调试
  console.log('接收到的file对象结构:', file);

  // 查找要移除的文件在fileList中的索引
  const index = fileList.value.findIndex(f => f.uid === file.uid);

  // 如果找到了文件（即索引大于-1）
  if (index > -1) {
    // 从fileList中移除该文件
    fileList.value.splice(index, 1);

    // 释放与该文件关联的URL对象
    if (file.url && typeof file.url === 'string') {
      URL.revokeObjectURL(file.url);
    }
  }
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

const handleDownload = (file) => {
  console.log('下载文件相关逻辑待完善，当前文件信息:', file);
  // 这里可以添加实际的文件下载逻辑，比如调用浏览器下载接口或者与后端配合实现下载功能
};

const isImage = (filename) => {
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'];
  const ext = filename.slice(filename.lastIndexOf('.')).toLowerCase();
  return imageExtensions.includes(ext);
};

const openFile = (file) => {
  try {
    console.log(fileList);
    window.open(file.url, '_blank');
    console.log(fileList);
  } catch (error) {
    console.error('打开文件时出错:', error);
  }
};

const removeFile = (file) => {
  handleRemove(file); // 调用已有的 handleRemove 函数
};
</script>

<style scoped>
@import "../../assets/css/global.css";
:deep(.el-upload-dragger){
  background-color: rgba(255,255,255,0.51);;/*覆盖原背景颜色，设置成透明 */
}
.input-with-select1:deep(.el-input__wrapper) {
  background-color: #f9f7f7;/*覆盖原背景颜色，设置成透明 */
  border-radius: 0 10px 10px 0;
  outline: #3F72AF 1px solid;
}
:deep(.el-input-group__prepend) {
  background-color: #f9f7f7;/*覆盖原背景颜色，设置成透明 */
  border-radius: 10px 0  0 10px;
  outline: #3F72AF 1px solid;
}
:deep(.el-input__wrapper){
  background-color: #f9f7f7;/*覆盖原背景颜色，设置成透明 */
  border-radius: 10px;
  outline: #3F72AF 1px solid;
}
.button-group {
  display: flex;
  gap: 100px; /* 按钮之间的间隔 */
  margin-top: 30px;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  justify-content: center;
}

button {
  padding: 10px 40px;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  border-radius: 15px;
}

/* 活动状态按钮样式 */
.active {
  background-color: #3F72AF; /* 蓝色背景 */
  color: #f9f7f7; /* 白色文字 */
}

/* 非活动状态按钮样式 */
.inactive {
  background-color: #f9f7f7; /* 白色背景 */
  color: #3F72AF; /* 蓝色文字 */
}
.high_year{
  font-size: 24px;
  font-weight: bold;
  color: black;
  background-color: rgba(52,124,175,0.11);
}
.year{
  font-size: 22px;
  color: #444444;
}
.low_year{
  font-size: 16px;
  color: #888888;
}
.el-upload-list__item-container {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-around; /* 设置子元素之间的间距均匀分布 */
  align-items: center;
  gap: 10px; /* 缩略图之间的间距，如果需要可以调整 */
}
.el-upload-list__item {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 0;  /* 去掉原来的底部外边距 */
}
.el-upload-list__item-thumbnail {
  width: 250px;
  margin:auto;
}
.el-upload-list__item-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  margin-left: 5px;  /* 与缩略图间隔一点距离 */
}
.download-link {
  margin-left: 10px;
  cursor: pointer;
  text-decoration: underline;
}

</style>